layui.use(['jquery', 'febs', 'table', 'form', 'fileUpload', 'commonJS', 'formSelects', 'validate'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        formSelects = layui.formSelects,
        $view = $('#task-edit'),
        $taskCode = $view.find('#taskCode'),
        laydate = layui.laydate,
        $projectCode = $view.find('#projectCode'),
        $rsid = $view.find('#rsid'),
        $paiqi = $view.find('#paiqi'),
        $changshui = $view.find('#changshui'),
        $banliu = $view.find('#banliu'),
        $liuxiang = $view.find('#liuxiang'),
        $status = $view.find('#status'),
        $iskeyTask = $view.find('#iskeyTask'),
        $taskType = $view.find('#taskType'),
        fileUpload = layui.fileUpload,
        commonJS = layui.commonJS,
        validate = layui.validate;
    initDictSelect();
    form.verify(validate);
    formSelects.render();
    renderDate('#planStartdate', 'yyyy-MM-dd');
    renderDate('#planEnddate', 'yyyy-MM-dd');


    form.render();
    initFormValue();
    var taskTestData = taskData.taskTestArray || [];
    var testTestcsArray = taskData.taskTestcsArray || [];
    var testTestbl1Array = taskData.taskTestbl1Array || [];
    var testTestbl2Array = taskData.taskTestbl2Array || [];
    var testTestlxArray = taskData.taskTestlxArray || [];
    if (taskData.taskType == 1) {
        initTestTable(taskTestData);
    } else if (taskData.taskType == 2) {
        initTestTablecs(testTestcsArray);
    } else if (taskData.taskType == 3) {
        $paiqi.css('display', 'none');
        $changshui.css('display', 'none');
        $banliu.css('display', 'block');
        $liuxiang.css('display', 'none');
        initTestTablebl1(testTestbl1Array);
        initTestTablebl2(testTestbl2Array);
    } else if (taskData.taskType == 4) {
        initTestTablelx(testTestlxArray);
    }

    var iskey = taskData.iskeyTask;



    form.on('select(projectCode)', function (data) {
        initMultiSelect(data.value, '');
    });


    formSelects.on('modelids', function (id, vals, val, isAdd, isDisabled) {
        var tasktype = $taskType.val();
        if (tasktype == '') {

        } else {
            if (isAdd) {
                var selectData = vals || [];
                selectData.push(val);
                var ids = [];
                selectData.forEach(item => {
                    ids.push(item.value);
                })
                $("[name='modelids']").val(ids.join(","));
            } else {
                var selectData = vals || [];
                for (var key in selectData) {
                    if (selectData[key].value == val.value) {
                        selectData.splice(key, 1);
                    }
                }
                var ids = [];
                selectData.forEach(item => {
                    ids.push(item.value);
                })
                $("[name='modelids']").val(ids.join(","));
            }
            initTest(tasktype)
        }
    });


    form.on('select(taskType)', function (data) {
        if (data.value == '') {

        } else {
            initTest(data.value)
        }
    });

    function initTest(taskType) {
        if (taskType == 1) {
            initTestTable(taskTestData);
        } else if (taskType == 2) {
            var modelids = $("[name='modelids']").val();
            debugger;
            var arr = modelids.split(",") || [];
            arr = arr.filter(obj => obj.startsWith("jm_")) || [];
            var codes = [];
            arr.forEach(item => {
                codes.push(item.substring(3, item.length));
            })
            testTestcsArray = updateTable(codes, testTestcsArray, 'oarsCode');
            initTestTablecs(testTestcsArray);
        } else if (taskType == 3) {
            $paiqi.css('display', 'none');
            $changshui.css('display', 'none');
            $banliu.css('display', 'block');
            $liuxiang.css('display', 'none');

            var modelids = $("[name='modelids']").val();
            var arr = modelids.split(",") || [];
            var arr1 = arr.filter(obj => obj.startsWith("cm_")) || [];
            var codes1 = [];
            arr1.forEach(item => {
                codes1.push(item.substring(3, item.length));
            })
            testTestbl1Array = updateTable(codes1, testTestbl1Array, 'shipCode');
            initTestTablebl1(testTestbl1Array);

            var arr2 = arr.filter(obj => obj.startsWith("jm_")) || [];
            var codes2 = [];
            arr2.forEach(item => {
                codes2.push(item.substring(3, item.length));
            })
            testTestbl2Array = updateTable(codes2, testTestbl2Array, 'oarsCode');
            initTestTablebl2(testTestbl2Array);

        } else if (taskType == 4) {
            var modelids = $("[name='modelids']").val();
            var arr = modelids.split(",") || [];
            arr = arr.filter(obj => obj.startsWith("cm_")) || [];
            var codes = [];
            arr.forEach(item => {
                codes.push(item.substring(3, item.length));
            })
            testTestlxArray = updateTable(codes, testTestlxArray, 'shipcode');
            initTestTablelx(testTestlxArray);
        }

    }


    //新的添加，老的删除，已有的以原数据为准
    function updateTable(codes, datas, fieldname) {
        if (datas == null || datas.length == 0) {
            codes.forEach(code => {
                obj = {
                    [fieldname]: code,
                }
                datas.push(obj);
            });
        } else {
            datas = datas.filter(obj => codes.includes(obj.fieldname));
            var datacodes = [];
            datas.forEach(item => datacodes.putsh(item.fieldname));
            codes.forEach(item => {
                if (!datacodes.includes(item)) {
                    obj = {
                        [fieldname]: item,
                    }
                    datas.push(obj);
                }
            })
        }
        return datas;
    }


    function initfile() {
        var fileUploadDiv1 = fileUpload.render({
            elem: '#fileUploadBtn',
            url: ctx + 'task/upload',
            type: 2,//0-图片，1-视频，2-其他
            maxNum: 5,
            multiple: true,
            defaultData: taskData && taskData.fileList ? taskData.fileList : [],
            isDetail: false,
            done: function (res) {
            },
            error: function () {
                layer.msg("服务器异常");
            }
        });
    }

    function initTestTable(data) {
        debugger;
        $paiqi.css('display', 'block');
        $changshui.css('display', 'none');
        $banliu.css('display', 'none');
        $liuxiang.css('display', 'none');
        tasktableIns = febs.table.init({
            elem: '#tasktestTable',
            data: data,
            page: false,
            loading: false,
            even: false,
            height: getTableHeight() / 3,
            width:1086,
            cols: [[
                {field: 'id', title: 'id', minWidth: 20,  hide: true},
                {field: 'no', title: '序号', type: 'number', minWidth: 10, edit: false, sort: false},
                {field: 'resistance', title: '阻力', minWidth: 100, edit: false},
                {field: 'navigate', title: '自航(吃水数量/航速个数,PK试验航速数量,不同时可新增几行1/3、1/2等)'
                        , minWidth: 426, edit: false},
                {field: 'seakeep', title: '耐波', minWidth: 100, edit: false},
                {field: 'controll', title: '操纵', minWidth: 100, edit: false},
                {field: 'vain', title: '空泡', minWidth: 100, edit: false},
                {title: '操作', minWidth: 150, toolbar: '#toolbarRow', align: 'left'},
            ]],
            toolbar: '#toolbarDemo',
            defaultToolbar: [],
            done: function (res, curr, count) {
            }
        });
        return tasktableIns;
    }

    function initTestTablecs(data) {
        $paiqi.css('display', 'none');
        $changshui.css('display', 'block');
        $banliu.css('display', 'none');
        $liuxiang.css('display', 'none');
        tasktableIns = febs.table.init({
            elem: '#tasktestTablecs',
            data: data,
            page: false,
            loading: false,
            even: false,
            height: getTableHeight() / 3,
            skin: '',
            width:940,
            cols: [[
                {field: 'id', title: 'id', minWidth: 20, hide: true},
                {field: 'oarsCode', title: '桨模编号', minWidth: 120, edit: false},
                {field: 'diameter', title: '桨模直径(mm)', minWidth: 100, edit: false},
                {field: 'pitch', title: '螺距比', minWidth: 100, edit: false},
                {field: 'surface', title: '盘面比', minWidth: 100, edit: false},
                {field: 'chord', title: '弦长(mm)', minWidth: 100, edit: false},
                {field: 'leaf', title: '叶厚(mm)', minWidth: 100, edit: false},
                {field: 'remark', title: '备注', minWidth: 120, edit: false},
                {title: '操作', minWidth: 150, align: 'left', templet: function (d) {
                        return '<div className="layui-btn-container">' +
                            '<button className="layui-btn layui-btn-sm" type="button" lay-event="editcs">编辑行</button>'
                            + '</button></div>';
                    }
                },
            ]],
            defaultToolbar: [],
            done: function (res, curr, count) {
            }
        });
        return tasktableIns;
    }

    function initTestTablelx(data) {
        $paiqi.css('display', 'none');
        $changshui.css('display', 'none');
        $banliu.css('display', 'none');
        $liuxiang.css('display', 'block');
        tasktableIns = febs.table.init({
            elem: '#tasktestTablelx',
            data: data,
            page: false,
            loading: false,
            even: false,
            height: getTableHeight() / 3,
            width: 850,
            cols: [[
                {field: 'id', title: 'id', minWidth: 20, hide: true},
                {field: 'shipcode', title: '船模编号', minWidth: 120, edit: false},
                {field: 'draugh', title: '吃水', minWidth: 120, edit: false},
                {field: 'displacement', title: '排水', minWidth: 120, edit: false},
                {field: 'speed', title: '船模速度', minWidth: 120, edit: false},
                {field: 'remark', title: '备注', minWidth: 120, edit: false},
                {
                    title: '操作', minWidth: 200, align: 'left', templet: function (d) {
                        return '<div className="layui-btn-container">' +
                            '<button className="layui-btn layui-btn-sm" type="button" lay-event="editlx">编辑行</button>'
                            + '</button></div>';
                    }
                },
            ]],
            defaultToolbar: [],
            done: function (res, curr, count) {
            }
        });
        return tasktableIns;
    }

    function initTestTablebl1(data) {
        tasktableIns = febs.table.init({
            elem: '#tasktestTablebl1',
            data: data,
            page: false,
            loading: false,
            even: false,
            height: getTableHeight() / 3,
            width: 850,
            cols: [[
                {field: 'id', title: 'id', minWidth: 20, hide: true},
                {field: 'shipCode', title: '船模编号', minWidth: 120, edit: false},
                {field: 'draugh', title: '吃水', minWidth: 120, edit: false},
                {field: 'displacement', title: '排水', minWidth: 120, edit: false},
                {field: 'speed', title: '船模速度', minWidth: 120, edit: false},
                {field: 'remark', title: '备注', minWidth: 120, edit: false},
                {
                    title: '操作', minWidth: 200, align: 'left', templet: function (d) {
                        return '<div className="layui-btn-container">' +
                            '<button className="layui-btn layui-btn-sm" type="button" lay-event="editbl1">编辑行</button>'
                            + '</button></div>';
                    }
                },
            ]],
            defaultToolbar: [],
            done: function (res, curr, count) {
            }
        });
        return tasktableIns;
    }


    function initTestTablebl2(data) {
        tasktableIns = febs.table.init({
            elem: '#tasktestTablebl2',
            data: data,
            page: false,
            loading: false,
            even: false,
            height: getTableHeight() / 3,
            width: 850,
            cols: [[
                {field: 'id', title: 'id', minWidth: 20, hide: true},
                {field: 'oarsCode', title: '桨模编号', minWidth: 120, edit: false},
                {field: 'diameter', title: '直径mm', minWidth: 120, edit: false},
                {field: 'surface', title: '桨盘面距尾轴出口长度mm', minWidth: 120, edit: false},
                {field: 'direct', title: '桨模旋向', minWidth: 120, edit: false},
                {field: 'remark', title: '备注', minWidth: 120, edit: false},
                {
                    title: '操作', minWidth: 200, align: 'left', templet: function (d) {
                        return '<div className="layui-btn-container">' +
                            '<button className="layui-btn layui-btn-sm" type="button" lay-event="editbl2">编辑行</button>'
                            + '</button></div>';
                    }
                },
            ]],
            defaultToolbar: [],
            done: function (res, curr, count) {
            }
        });
        return tasktableIns;
    }


    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    function renderDate(element, format) {
        laydate.render({
            elem: element,
            type: 'date',
            format: format,
            btns: ['now', 'confirm'],
            trigger: 'click',
            isInitValue: true
        });
    }

    function initMultiSelect(projectCode, taskCode) {
        formSelects.config('modelids', {
            searchUrl: ctx + 'task/getModelList',
            data: {projectCode: projectCode, taskCode: taskCode},
            response: {
                statusCode: 200
            },
            beforeSuccess: function (id, url, searchVal, result) {
                var data = result.data;
                var tranData = [];
                if (data != null) {
                    for (var i = 0; i < data.length; i++) {
                        var  shortname=  data[i].code.slice(0,3);
                        var  showname=data[i].code.slice(3);
                        if(shortname=='cm_'){
                            showname='船模'+showname;
                        }else if(shortname=='jm_'){
                            showname='桨模'+showname;
                        }else  if(shortname=='ft_'){
                            showname='附体'+showname;
                        }
                        tranData.push({
                            name:showname,
                            value: data[i].code
                        })
                    }
                }
                result.data = tranData;
                return result;
            },
            success: function () {
                formSelects.value('modelids',
                taskData.modelids == null ? [] : taskData.modelids.split(','));
            },
            error: function (id, url, searchVal, err) {
                console.error(err);
                febs.alert.error('获取列表失败');
            }
        });
    }


    function initDictSelect() {
        febs.initDictItemSelect($taskType, "TASK_TYPE", taskData.taskType, "");
        febs.initDictItemSelect($status, "TASK_STATUS", taskData.status, "");
        initProjectOptions($projectCode, projectListData, taskData.projectCode, "");
        initResourceOptions($rsid, resourceListData, taskData.rsid, "");
        if (taskData.createdTime != null) {
            $taskCode.attr("readonly", true);
            initMultiSelect(taskData.projectCode, taskData.taskCode);
        } else {
            initMultiSelect(taskData.projectCode, '');
        }
        initfile();
    }


    function initProjectOptions(element, data, defaultValue, callBack) {
        $(element).empty();
        $(element).append(`<option value="">请选择</option>`);
        if (data != null && data.length > 0) {
            data.forEach(item => {
                if (defaultValue == item.projectCode) {
                    element.append(`<option value="${item.projectCode}"  selected>${item.projectCode}</option>`)
                } else {
                    element.append(`<option value="${item.projectCode}" >${item.projectCode}</option>`)
                }
            })
        }
        if (typeof (callBack) === "function") {
            callBack(result);
        }
        layui.form.render('select')
    }

    function initResourceOptions(element, data, defaultValue, callBack) {
        $(element).empty();
        $(element).append(`<option value="">请选择</option>`);
        if (data != null && data.length > 0) {
            data.forEach(item => {
                if (defaultValue == item.rsid) {
                    element.append(`<option value="${item.id}"  selected>${item.rsName}</option>`)
                } else {
                    element.append(`<option value="${item.id}" >${item.rsName}</option>`)
                }
            })
        }
        if (typeof (callBack) === "function") {
            callBack(result);
        }
        layui.form.render('select');
    }

    function initFormValue() {
        if (taskData) {
            form.val("task-edit-form", {
                "taskCode": taskData.taskCode,
                "projectCode": taskData.projectCode,
                "modelids": taskData.modelids,
                "taskType": taskData.taskType,
                "status": taskData.status,
                "testDay": taskData.testDay,
                "iskeyTask": taskData.iskeyTask,
                "keyExplain":taskData.keyExplain,
                "remark": taskData.remark,
                "planStartdate": taskData.planStartdate,
                "planStarttime": taskData.planStarttime,
                "planEnddate": taskData.planEnddate,
                "planEndtime": taskData.planEndtime,
                "actuallyStartdate": taskData.actuallyStartdate,
                "actuallyEnddate": taskData.actuallyEnddate,
                "createdTime": taskData.createdTime,
                "rsid": taskData.rsid,
            });
        }
        //要放在form后面渲染， checkbox中根据name获取结果不正确
        if (taskData.iskeyTask === '1') {
            $iskeyTask.prop("checked", true);
            $("#explainCss").css("display","block");
        } else {
            $iskeyTask.prop("checked", false);
            $("#explainCss").css("display","none");
        }
        form.render('checkbox');
    }

    form.on('submit(task-edit-form-save)', function (data) {
      var  data=data.field
        if(data.taskType==1&& oneDecimal(data.testDay)==false){
            febs.alert.warn('排期任务试验工时不能为空,且为0.5的整数倍!');
            return ;
        }
        addOrUpdate(data);
        return false;
    });


    form.on('submit(task-edit-form-saveAndNew)', function (data) {
        var data=data.field;
        if(data.taskType==1&& oneDecimal(data.testDay)==false){
            febs.alert.warn('排期任务试验工时不能为空,且为0.5的整数倍!');
            return ;
        }
        saveAndNew(data);
        return false;
    });


    form.on('checkbox(iskeyTask)', function (data) {
        if (data.elem.checked) {
            iskey = '1';
            $("#explainCss").css("display","block");
        } else {
            iskey = '0';
            $("#explainCss").css("display","none");
        }
    });

    function addOrUpdate(data) {
        data.fileList = getFileData();
        data.iskeyTask = iskey;
        if(iskey=='1' &&data.keyExplain==''){
            febs.alert.warn('重点任务的说明不能为空!');
            return;
        }
        data.taskTestArray = taskTestData || [];
        data.taskTestcsArray = testTestcsArray || [];
        data.taskTestbl1Array = testTestbl1Array || [];
        data.taskTestbl2Array = testTestbl2Array || [];
        data.taskTestlxArray = testTestlxArray || [];

        if (!(data.modelids != null && data.modelids == taskData.modelids
                && data.testDay == taskData.testDay && data.rsid == taskData.rsid) &&
            taskData.status != null && (taskData.status == 4 || taskData.status == 5)) {
            layer.confirm('对于已排期、试验中的任务，修改了所需模型、所需资源或试验工，导致原已排期的计划有变,'+
                '原排期失效，请重新排期！',{icon:3,btn:['确定','取消'],
                yes:function (index,layero){
                    if (data.createdTime != null && data.createdTime != '') {
                        febs.postArray(ctx + 'task/update', data, function () {
                            layer.closeAll();
                            febs.alert.success('修改成功');
                            var currentUrl = window.location.hash.replace('#', '');
                            febs.view.tab.del(currentUrl);
                            febs.view.tab.change("/task");
                            $('#febs-task').find('#query').trigger('click');
                        });
                    } else {
                        var checkResult = getData(ctx + 'task/check', {
                            taskCode: data.taskCode,
                        });
                        if (checkResult.length > 0) {
                            febs.alert.warn(checkResult);
                            return;
                        }

                        febs.postArray(ctx + 'task', data, function () {
                            layer.closeAll();
                            febs.alert.success('新增成功');
                            var currentUrl = window.location.hash.replace('#', '');
                            febs.view.tab.del(currentUrl);
                            febs.view.tab.change("/task");
                            $('#febs-task').find('#query').trigger('click');
                        });
                    }
                    layer.close(index);
                },close() {
                    layer.closeAll();
                }
            });
        } else {
            febs.modal.confirm("提交提示", "是否提交？", function (index) {
                if (data.createdTime != null && data.createdTime != '') {
                    febs.postArray(ctx + 'task/update', data, function () {
                        layer.closeAll();
                        febs.alert.success('修改成功');
                        var currentUrl = window.location.hash.replace('#', '');
                        febs.view.tab.del(currentUrl);
                        febs.view.tab.change("/task");
                        $('#febs-task').find('#query').trigger('click');
                    });
                } else {
                    var checkResult = getData(ctx + 'task/check', {
                        taskCode: data.taskCode,
                    });
                    if (checkResult.length > 0) {
                        febs.alert.warn(checkResult);
                        return;
                    }
                    febs.postArray(ctx + 'task', data, function () {
                        layer.closeAll();
                        var currentUrl = window.location.hash.replace('#', '');
                        febs.view.tab.del(currentUrl);
                        febs.view.tab.change("/task");
                        febs.alert.success('新增成功');
                        $('#febs-task').find('#query').trigger('click');
                    });
                }
            });
        }

    }

function saveAndNew(data) {
    data.fileList = getFileData();
    data.iskeyTask = iskey;
    if(iskey=='1' &&data.keyExplain==''){
        febs.alert.warn('重点任务的说明不能为空!');
        return;
    }
    data.taskTestArray = taskTestData || [];
    data.taskTestcsArray = testTestcsArray || [];
    data.taskTestbl1Array = testTestbl1Array || [];
    data.taskTestbl2Array = testTestbl2Array || [];
    data.taskTestlxArray = testTestlxArray || [];

    if (!(data.modelids != null && data.modelids == taskData.modelids
            && data.testDay == taskData.testDay && data.rsid == taskData.rsid) &&
        taskData.status != null && (taskData.status == 4 || taskData.status == 5)) {
         layer.confirm('对于已排期、试验中的任务,修改了所需模型、所需资源或试验工，导致原已排期的计划有变,' +
             '原排期失效，请重新排期!',{icon:3,btn:['确认','取肖'],title:'询问',
             yes: function (index, layero) {
                 if (data.createdTime != null && data.createdTime != '') {
                     febs.postArray(ctx + 'task/update', data, function () {
                         layer.closeAll();
                         var currentUrl = window.location.hash.replace('#', '');
                         febs.view.tab.del(currentUrl);
                         febs.view.tab.change("/task");
                         $('#febs-task').find('#query').trigger('click');
                         openModal();
                     });
                 } else {
                     febs.postArray(ctx + 'task', data, function () {
                         layer.closeAll();
                         var currentUrl = window.location.hash.replace('#', '');
                         febs.view.tab.del(currentUrl);
                         febs.view.tab.change("/task");
                         $('#febs-task').find('#query').trigger('click');
                         openModal();
                     });
                 }

             },btn2:function (index,layero){
                 layer.closeAll();
             }
         });
      }else {
          febs.modal.confirm("提交提示！", "是否提交？", function (index) {
            if (data.createdTime != null && data.createdTime != '') {
                febs.postArray(ctx + 'task/update', data, function () {
                    layer.closeAll();
                    var currentUrl = window.location.hash.replace('#', '');
                    febs.view.tab.del(currentUrl);
                    febs.view.tab.change("/task");
                    $('#febs-task').find('#query').trigger('click');
                    openModal();
                });
            } else {
                var checkResult = getData(ctx + 'task/check', {
                    taskCode: data.taskCode,
                });
                if (checkResult.length > 0) {
                    febs.alert.warn(checkResult);
                    return;
                }

                febs.postArray(ctx + 'task', data, function () {
                    layer.closeAll();
                    var currentUrl = window.location.hash.replace('#', '');
                    febs.view.tab.del(currentUrl);
                    febs.view.tab.change("/task");
                    $('#febs-task').find('#query').trigger('click');
                    openModal();
                });
            }
          });
    }

}

function openModal() {
    parent.layui.febs.navigate("/task/add",true);
}


function getFileData() {
    var fileDatas = $view.find(".fileOne")
    var list = [];
    $.each(fileDatas, function (index, item) {
        var data = {
            filePath: item.dataset.filepath,
            fileName: item.dataset.filename,
            smallPath: item.dataset.smallpath,
        }
        list.push(data);
    })
    return list;
}



  function   oneDecimal(value, item) {
      //  正则表达式，匹配一位小数
        if(value==''||value==undefined){
            return  false;
        }
        if (/^\d+(.{0,1}[0|5]{0,1})?$/.test(value)) {
            return true;
        }
        return  false;
    }


//监听头部工具条
table.on('toolbar(tasktestTable)', function (obj) {
    layEvent = obj.event; //获得 lay-event 对应的值
    var options = obj.config; // 获取当前表格属性配置项
    if (layEvent === 'addrow') {
        var no = 1;
        var id = 1;
        taskTestData.forEach(item => {
            if (item != null && item.no != null && item.no >= no) {
                no = parseInt(item.no) + 1;
            }
            if (item != null && item.id != null && item.id >= id) {
                id = parseInt(item.id) + 1;
            }
        });
        var param = "?id=" + id + "&no=" + no + "&resistance=&navigate=&seakeep=&controll=&vain=";
        febs.modal.open('增加行', 'taskTest/row' + param, {
            area: $(window).width() <= 750 ? ['50%', '500px'] : ['50%', '500px'],
            btn: ['提交', '取消'],
            yes: function (index, layero) {
                $('#taskTest-edit').find('#submit').trigger('click');
               var   result= $(layero).find("#verifyResult").val();
                if(result=='true'){
                    layer.close(index);
                }else{
                    $(layero).find("#verifyResult").val('true');
                }
            },
            btn2: function (index, layno) {
                layer.close(index);
            },
            data: {}
        });

    }
});
//表体工具栏
table.on('tool(tasktestTable)', function (obj) {
    var data = obj.data || [] //获得当前行数据
    layEvent = obj.event; //获得 lay-event 对应的值
    if (layEvent === 'editrow') {
        var param = "?id=" + data.id + "&no=" + data.no + "&resistance=" + data.resistance + "&navigate=" + data.navigate
            + "&seakeep=" + data.seakeep + "&controll=" + data.controll + "&vain=" + data.vain;
        febs.modal.open('修改行', 'taskTest/row' + param, {
            area: $(window).width() <= 750 ? ['50%', '500px'] : ['50%', '500px'],
            btn: ['提交', '取消'],
            yes: function (index, layero) {
                //  $('#taskTest-edit-form').find('#submit').trigger('click');
                $('#taskTest-edit').find('#submit').trigger('click');
                var   result= $(layero).find("#verifyResult").val();
                if(result=='true'){
                    layer.close(index);
                }else{
                    $(layero).find("#verifyResult").val('true');
                }
            },
            btn2: function (index, layno) {
                layer.close(index);
            },
            data: {}
        });

    } else if (layEvent === 'delrow') {
        febs.modal.confirm('删除数据', '确定删除所选数据？', function () {
            for (var key in taskTestData) {
                if (taskTestData[key].id = data.id) {
                    taskTestData.splice(key, 1);
                }
            }
            initTestTable(taskTestData);
        });
    }
});

table.on('tool(tasktestTablecs)', function (obj) {
    var data = obj.data || [] //获得当前行数据
    layEvent = obj.event; //获得 lay-event 对应的值
    var id = data.id;
    if (data.id == undefined || data.id == '') {
        id = 0;
    }

    var param = "id=" + id + "&oarsCode=" + data.oarsCode + "&diameter=" + data.diameter +
        "&pitch=" + data.pitch + "&surface=" + data.surface + "&chord=" + data.chord + "&leaf=" + data.leaf + "&remark=" + data.remark;
    if (layEvent === 'editcs') {
        febs.modal.open('修改行', 'taskTestcs/row?' + param, {
            area: $(window).width() <= 750 ? ['50%', '500px'] : ['50%', '500px'],
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                $('#taskTestcs-edit').find('#submit').trigger('click');
                layer.close(index);
            },
            btn2: function (index, layno) {
                layer.close(index);
            },
            data: {data}
        });
    }
});


table.on('tool(tasktestTablelx)', function (obj) {
    var data = obj.data || [] //获得当前行数据
    layEvent = obj.event; //获得 lay-event 对应的值
    var id = data.id;
    if (data.id == undefined || data.id == '') {
        id = 0;
    }

    var param = "id=" + id + "&shipcode=" + data.shipcode + "&draugh=" + data.draugh +
        "&displacement=" + data.displacement + "&speed=" + data.speed + "&remark=" + data.remark;
    if (layEvent === 'editlx') {
        febs.modal.open('修改行', 'taskTestlx/row?' + param, {
            area: $(window).width() <= 750 ? ['50%', '420px'] : ['50%', '420px'],
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                $('#taskTestlx-edit').find('#submit').trigger('click');
                layer.close(index);
            },
            btn2: function (index, layno) {
                layer.close(index);
            },
            data: {data}
        });
    }
});


table.on('tool(tasktestTablebl1)', function (obj) {
    var data = obj.data || [] //获得当前行数据
    layEvent = obj.event; //获得 lay-event 对应的值
    var id = data.id;
    if (data.id == undefined || data.id == '') {
        id = 0;
    }

    var param = "id=" + id + "&shipCode=" + data.shipCode + "&draugh=" + data.draugh +
        "&displacement=" + data.displacement + "&speed=" + data.speed + "&remark=" + data.remark;
    if (layEvent === 'editbl1') {
        febs.modal.open('修改行', 'taskTestbl1/row?' + param, {
            area: $(window).width() <= 750 ? ['50%', '390px'] : ['50%', '390px'],
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                $('#taskTestbl1-edit').find('#submit').trigger('click');
                layer.close(index);
            },
            btn2: function (index, layno) {
                layer.close(index);
            },
            data: {data}
        });
    }
});


table.on('tool(tasktestTablebl2)', function (obj) {
    var data = obj.data || [] //获得当前行数据
    layEvent = obj.event; //获得 lay-event 对应的值
    var id = data.id;
    if (data.id == undefined || data.id == '') {
        id = 0;
    }

    var param = "id=" + id + "&oarsCode=" + data.oarsCode + "&diameter=" + data.diameter +
        "&surface=" + data.surface + "&direct=" + data.direct + "&remark=" + data.remark;
    if (layEvent === 'editbl2') {
        febs.modal.open('修改行', 'taskTestbl2/row?' + param, {
            area: $(window).width() <= 750 ? ['50%', '406px'] : ['50%', '406px'],
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                $('#taskTestbl2-edit').find('#submit').trigger('click');
                layer.close(index);
            },
            btn2: function (index, layno) {
                layer.close(index);
            },
            data: {data}
        });
    }
});

    function  isDecimal(value, item){
        if(value==''||value==undefined){
            return false
        }
        if (/^\d+(.{0,1}\d+)?$/.test(value)) {
            return true;
        }
        return  false;
    }

form.on("submit(taskTest-edit-form-submit)", function (rowdata) {
    var row = rowdata.field;
    if(!isDecimal(row.no)){
        febs.alert.warn('序号请输入数字!');
        $("#verifyResult").val("false");
        return  false ;
    }
    if(!isDecimal(row.resistance)){
        febs.alert.warn('阻力请输入数字!');
        $("#verifyResult").val("false");
        return  false ;
    }
    if(!isDecimal(row.navigate1)||!isDecimal(row.navigate2)){
        febs.alert.warn('吃水数量/航速个数请输入数字!');
        $("#verifyResult").val("false");
        return  false ;
    }

    if(!isDecimal(row.seakeep)){
        febs.alert.warn('耐波请输入数字!');
        $("#verifyResult").val("false");
        return  false ;
    }
    if(!isDecimal(row.controll)){
        febs.alert.warn('操纵请输入数字!');
        $("#verifyResult").val("false");
        return   false;
    }
    if(!isDecimal(row.vain)){
        febs.alert.warn('空泡请输入数字!');
        $("#verifyResult").val("false");
        return  false ;
    }
    row.navigate = row.navigate1 + '/' + row.navigate2;
    var isnew = true;
    taskTestData.forEach(item => {
        if (item.id == row.id) {
            item.no = row.no;
            item.resistance = row.resistance;
            item.navigate = row.navigate;
            item.seakeep = row.seakeep;
            item.controll = row.controll;
            item.vain = row.vain;
            isnew = false;

        }
    });
    if (isnew) {
        taskTestData.push(row);
    }
    taskTestData.sort(function (a, b) {
        return a.no - b.no;
    })
    initTestTable(taskTestData);
    return false;
});


form.on('submit(taskTestcs-edit-form-submit)', function (data) {
    var row = data.field;
    testTestcsArray.forEach(item => {
        if (item.oarsCode == row.oarsCode) {
            item.id = row.id;
            item.oarsCode = row.oarsCode;
            item.diameter = row.diameter;
            item.pitch = row.pitch;
            item.surface = row.surface;
            item.chord = row.chord;
            item.leaf = row.leaf;
            item.remark = row.remark;
        }
    })
    initTestTablecs(testTestcsArray);
});

form.on('submit(taskTestlx-edit-form-submit)', function (data) {
    var row = data.field;
    testTestlxArray.forEach(item => {
        if (item.shipcode == row.shipcode) {
            item.id = row.id;
            item.draugh = row.draugh;
            item.displacement = row.displacement;
            item.speed = row.speed;
            item.remark = row.remark;
        }
    })
    initTestTablelx(testTestlxArray);
    return false;
});

form.on('submit(taskTestbl1-edit-form-submit)', function (data) {
    var row = data.field;
    testTestbl1Array.forEach(item => {
        if (item.shipCode == row.shipCode) {
            item.id = row.id;
            item.draugh = row.draugh;
            item.displacement = row.displacement;
            item.speed = row.speed;
            item.remark = row.remark;
        }
    })
    initTestTablebl1(testTestbl1Array);
    return false;
});

form.on('submit(taskTestbl2-edit-form-submit)', function (data) {
    var row = data.field;
    testTestbl2Array.forEach(item => {
        if (item.oarsCode == row.oarsCode) {
            item.id = row.id;
            item.diameter = row.diameter;
            item.surface = row.surface;
            item.direct = row.direct;
            item.remark = row.remark;
        }
    })
    initTestTablebl2(testTestbl2Array);
    return false;
});


    function getData(url, condition) {
        var result;
        $.ajax({
            type: "get",
            dataType: "json",
            url: url,
            data: condition,
            cache: false,
            async: false,
            success: function (data) {
                console.log(data);
                result = data.data ;
            }
        });
        return result;
    }


})
